# manual_process_news.py
import sys
import os

sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from app import create_app, db
from models.models import RawNews, ProcessedNews
from celery_worker import process_news_task

def manual_process_unprocessed_news():
    """手动处理未处理的新闻"""
    app = create_app()

    with app.app_context():
        # 查找所有未处理的新闻
        unprocessed_news = RawNews.query.filter_by(processed=False).all()

        print(f"找到 {len(unprocessed_news)} 条未处理的新闻")

        if len(unprocessed_news) == 0:
            print("没有需要处理的新闻")
            return

        # 手动处理每条新闻
        for news in unprocessed_news:
            print(f"正在处理新闻: {news.title}")
            try:
                # 直接调用处理函数（而不是通过Celery）
                process_news_task(news.id)
                print(f"  ✓ 处理完成: {news.title}")
            except Exception as e:
                print(f"  ✗ 处理失败: {news.title} - 错误: {str(e)}")

        # 显示处理结果
        print("\n处理后统计:")
        total_raw = RawNews.query.count()
        processed_raw = RawNews.query.filter_by(processed=True).count()
        unprocessed_raw = RawNews.query.filter_by(processed=False).count()
        total_processed = ProcessedNews.query.count()

        print(f"  原始新闻总数: {total_raw}")
        print(f"  已处理原始新闻: {processed_raw}")
        print(f"  未处理原始新闻: {unprocessed_raw}")
        print(f"  处理后新闻总数: {total_processed}")

        # 显示处理后的新闻详情
        print("\n处理后的新闻详情:")
        processed_news_list = ProcessedNews.query.all()
        for news in processed_news_list:
            print(f"  标题: {news.title}")
            print(f"  评分: {news.news_score}")
            print(f"  品牌: {news.involved_brands}")
            print(f"  主题: {news.topics}")
            print(f"  摘要: {news.board_summary}")
            print("  " + "-" * 40)

if __name__ == '__main__':
    manual_process_unprocessed_news()
